import 'dart:async';

import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/device/application/notification/device_discovery_provider.dart';
import 'package:casdon/modules/device/application/notification/pair_net_notifier.dart';
import 'package:casdon/modules/device/domain/states/pair_state.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

// 这里主要用于引导配网，nfc配网，二维码配网等已知pid的情况下进行搜索对应设备并配网的场景
class DevicePairingNotifier extends AutoDisposeNotifier<DevicePairState> {
  @override
  DevicePairState build() {
    // 关键：在build中watch以建立持久依赖
    // final _ = ref.watch(deviceDiscoveryProvider);
    // final _ = ref.watch(pairNetProvider);
    ref.watch(_dependencyKeeperProvider);
    ref.onDispose(() {
      Log.i('♻️ DevicePairingNotifier 释放');
    });
    return DevicePairState.initial();
  }

  /// 启动设备发现并等待特定设备
  Future<void> discoverAndPairDevice({
    required String targetPid,
    required String ssid,
    required String password,
    int timeoutSeconds = CommonConfig.pairNet_device_timeout, // 发现设备并配网设备的总计超时
  }) async {
    Log.i('🎯 开始发现并配网设备 pid: $targetPid');
    state = DevicePairState(
      deviceModel: null,
      state: PairState.idle,
      errorCode: 0,
      errorMsg: '',
    );
    ThingSmartDeviceModel? device;
    try {
      // 1. 启动设备发现（不等待）
      final discoveryState = ref.read(deviceDiscoveryProvider);
      if (discoveryState.devices.any((d) => d.productId == targetPid)) {
        Log.w('⚠️ 目标设备已在发现列表中，无需重新发现');
        device = discoveryState.devices.firstWhere(
          (d) => d.productId == targetPid,
        );
      } else {
        final discoveryNotifier = ref.read(deviceDiscoveryProvider.notifier);
        unawaited(discoveryNotifier.discoverDevices(timeOut: timeoutSeconds));
        // 2. 监听设备流，等待目标设备出现
        device = await _waitForTargetDevice(targetPid, timeoutSeconds);
      }

      // 3. 停止设备发现
      // await discoveryNotifier.stopDiscovery();

      // 4. 开始配网(不要await，否则会阻塞后续的状态监听)
      _startPairingProcess(device, ssid, password);
      // 5. 更新状态为配网中
      state = DevicePairState(
        deviceModel: device,
        state: PairState.idle,
        errorCode: 0,
        errorMsg: '',
      );
      // 监听配网状态
      await _monitorPairingStatus(device);
    } catch (e) {
      state = state = DevicePairState(
        deviceModel: device,
        state: PairState.failed,
        errorCode: 0,
        errorMsg: '',
      );
      Log.e('❌ 设备发现配网失败', e, StackTrace.current);
      rethrow;
    }
  }

  /// 等待特定设备出现
  Future<ThingSmartDeviceModel> _waitForTargetDevice(
    String targetPid,
    int timeoutSeconds,
  ) async {
    final completer = Completer<ThingSmartDeviceModel>();
    late StreamSubscription sub;
    Timer? timeoutTimer;

    // 设置超时
    timeoutTimer = Timer(Duration(seconds: timeoutSeconds), () {
      if (!completer.isCompleted) {
        state = DevicePairState(
          deviceModel: null,
          state: PairState.failed,
          errorCode: 0,
          errorMsg: '',
        );
        Log.i('✅ 未找到设备目标设备: ${targetPid}');
        completer.completeError(TimeoutException('未找到设备 $targetPid'));
      }
    });

    // 监听设备发现流
    sub = ref.read(deviceDiscoveryProvider.notifier).deviceStream.listen((
      device,
    ) {
      if (device.productId == targetPid && !completer.isCompleted) {
        Log.i('✅ 找到目标设备,: ${device.name}, ${device.productId}， 停止发现设备');
        completer.complete(device);
        ref.read(deviceDiscoveryProvider.notifier).stopDiscovery();

        timeoutTimer?.cancel();
        sub.cancel();
      }
    }, onError: completer.completeError);

    return completer.future;
  }

  /// 启动配网流程
  Future<void> _startPairingProcess(
    ThingSmartDeviceModel device,
    String ssid,
    String password,
  ) async {
    final pairNotifier = ref.read(pairNetProvider.notifier);
    try {
      Log.i('🔗 开始配网: ${device.name}, ${device.productId}');
      unawaited(
        pairNotifier.enqueueSinglePairings(
          devices: [device],
          ssid: ssid,
          password: password,
        ),
      );
    } catch (e) {
      state = DevicePairState(
        deviceModel: device,
        state: PairState.idle,
        errorCode: 0,
        errorMsg: '',
      );
      Log.e('⚡ 配网过程出错', e, StackTrace.current);
      rethrow;
    }
  }

  /// 监听配网状态
  Future<void> _monitorPairingStatus(ThingSmartDeviceModel device) async {
    final completer = Completer<void>();
    late final ProviderSubscription<List<DevicePairState>> localSub;
    localSub = ref.listen<List<DevicePairState>>(pairNetProvider, (pri, next) {
      final targetUuid = device.uuid?.toLowerCase() ?? '';
      final targetDevId = device.devId ?? '';
      final deviceState = next.firstWhere(
        (s) {
          final model = s.deviceModel;
          if (model == null) return false;
          final modelUuid = model.uuid?.toLowerCase() ?? '';
          final modelDevId = model.devId ?? '';
          if (targetUuid.isNotEmpty && modelUuid == targetUuid) return true;
          if (targetDevId.isNotEmpty && modelDevId == targetDevId) return true;
          return targetUuid.isEmpty && modelUuid.isEmpty;
        },
        orElse: () => DevicePairState(
          deviceModel: device,
          state: PairState.idle,
          errorCode: 0,
          errorMsg: '',
        ),
      );

      state = deviceState;
      switch (deviceState.state) {
        case PairState.success:
          Log.i(
            '🎉 配网成功: ${device.name}, ${device.productId} , ${device.devId}',
          );
          completer.complete();
          localSub.close();
          break;
        case PairState.failed:
          Log.e(
            '💥 配网失败: ${device.name}, ${device.productId} , ${device.devId}',
            Object(),
            StackTrace.current,
          );
          completer.completeError('配网失败');
          localSub.close();
          break;
        case PairState.process:
          Log.d(
            '⏳ 配网进行中:  ${device.name}, ${device.productId} , ${device.devId}',
          );
          break;
        case PairState.idle:
          break;
      }
    });

    // 设置配网超时
    Timer(Duration(seconds: CommonConfig.pairNet_device_timeout), () {
      if (!completer.isCompleted) {
        completer.completeError(TimeoutException('配网超时'));

        localSub.close();
      }
    });

    return completer.future;
  }
}

// final devicePairingServiceProvider = Provider<DevicePairingService>((ref) {
//   return DevicePairingService(ref);
// });

final devicePairingProvider =
    NotifierProvider.autoDispose<DevicePairingNotifier, DevicePairState>(
      () => DevicePairingNotifier(),
    );

// final devicePairingStateProvider = Provider<PairState>((ref) {
//   return ref.watch(devicePairingServiceProvider).currentState;
// });

// final devicePairingStateProvider =
//     StateProvider<PairState>((ref) => PairState.idle);
final _dependencyKeeperProvider = Provider.autoDispose<void>((ref) {
  // 在这里watch需要保持活跃的provider
  ref.watch(deviceDiscoveryProvider);
  ref.watch(pairNetProvider);
});
